package hk.ust.comp3111.ustnutrition.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.util.Log;

import com.couchbase.lite.*;

public class DataRow {
	static final String TAG = "DataField";
	
	public DataRow() {
		
	}
	
	DataTable<?> table;
	Document doc;
	List<Object> channels;
	
	public String getRev() {
		return doc == null ? null : doc.getCurrentRevisionId();
	}
	
	public String getId() {
		return doc == null ? null : doc.getId();
	}
	
	public void setTable(DataTable<?> table, Document doc) {
		delete();
		if(table != null) {
			this.table = table;
			this.doc = doc;
		}
	}
	
	public void setChannel(String channel) {
		if(channel == null)
			channels = null;
		else {
			channels = new ArrayList<Object>();
			channels.add(channel);
		}
		commit();
	}
	
	public boolean isPublic() {
		return channels != null && channels.size() > 0 && channels.get(0).toString().equals("public");
	}
	
	public boolean isNonPublic() {
		return channels != null && channels.size() > 0 && !channels.get(0).toString().equals("public");
	}
	
	public DataTable<?> getTable() {
		return table;
	}
	
	public void commit() {
		if(table != null) {
			Map<String, Object> obj = new HashMap<String, Object>();
			putInfo(obj);
			try {
				doc.putProperties(obj);
			} catch (CouchbaseLiteException e) {
				Log.e(TAG, "Cannot update field: " + e.getMessage());
			}
		} else
			throw new IllegalStateException();
	}
	
	public void refresh() {
		if(table != null) {
			Map<String, Object> obj = doc.getProperties();
			loadInfo(obj);
		} else
			throw new IllegalStateException();
	}
	
	@SuppressWarnings("unchecked")
	public void loadInfo(Map<String, Object> obj) {
		channels = (List<Object>)obj.get("channels");
	}
	
	public void putInfo(Map<String, Object> obj) {
		String rev = getRev();
		if(rev != null)
			obj.put("_rev", getRev());
		if(channels != null)
			obj.put("channels", channels);
	}
	
	public void delete() {
		if(table != null && doc != null) {
			table.removeCache(getId());
			try {
				doc.delete();
			} catch (CouchbaseLiteException e) {
				Log.e(TAG, "Cannot delete row");
			}
		}
		doc = null;
		table = null;
	}
    
    public static <T extends DataRow> T get(String key, Class<T> mclass) {
    	return DataAccessor.Instance.getTable(mclass).get(key);
    }
    
    public static <T extends DataRow> String getId(T item) {
    	if(item == null)
    		return null;
    	else
    		return item.getId();
    }
}


